package cn.tedu.controller;


import cn.tedu.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author JustOne
 * @title 上传图片(文件)
 * @notes 如题
 * @date 2023-04-28 11:33:49
 */
@RestController
@RequestMapping("/sps/upload")
@Slf4j
public class UploadController {
    /**
     * TODO:上线时请在yml中更改此值，
     * 用于指定上传图片保存的路径，具体请在配置文件中指定, 具体值为 [D:/myFile01]
     */
    @Value("${spring.upload-config.root-folder}")
    private String myDirPath;

    /**
     * 图片新名的前缀，具体值为 [/shop]
     */
    @Value("${spring.upload-config.http-prefix}")
    private String myPrefix;


    /**
     * 上传文件
     * @param pic
     * @return 文件的保存路径，给前端用于显示，例如【/shop/2023/04/8bc8bcf5-4e81-48ca-aced-94f0441cc80b.jpg】
     */
    @PostMapping("/imgs")
    public JsonResult doUploadImgs(MultipartFile[] pic){
        if(pic.length<=0){
            throw new RuntimeException("请选择图片");
        }
        Map<String, Object> result = new HashMap<String,Object>();
        for (int i = 0;i<pic.length;i++) {
            MultipartFile multipartFile = pic[i];
            log.info("收到的文件是:{}", multipartFile);
            String fileName = multipartFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
            //新的文件名是:8bc8bcf5-4e81-48ca-aced-94f0441cc80b.jpg
            log.info("新的文件名是:{}", fileName);

            Date date = new Date();
            String dateStr = "/"+new SimpleDateFormat("yyyy/MM/").format(date);
            String filePath = myDirPath + myPrefix + dateStr + fileName;
            //filePath是:D:/myFile01/shop/2023/04/8bc8bcf5-4e81-48ca-aced-94f0441cc80b.jpg
            log.info("filePath是:{}", filePath);

            File file = new File(filePath);
            if( !file.exists()){
                file.mkdirs();
            }

            try {
                multipartFile.transferTo(new File(filePath));
            } catch (IOException e) {
                String message = "上传失败";
                log.warn(message);
            }

            result.put("state", "SUCCESS");
            String hxUrl = myPrefix + dateStr + fileName;
            result.put("url",result.get("url")==null?hxUrl:result.get("url")+","+hxUrl);
        }

        return  JsonResult.success(result);
    }

    /**
     * 上传文件
     * @param pic
     * @return 文件的保存路径，给前端用于显示，例如【/shop/2023/04/8bc8bcf5-4e81-48ca-aced-94f0441cc80b.jpg】
     */
    @PostMapping("/insert")
    public JsonResult doUpload(MultipartFile pic){
        log.info("收到的文件是:{}", pic);
        String fileName = pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;
        //新的文件名是:8bc8bcf5-4e81-48ca-aced-94f0441cc80b.jpg
        log.info("新的文件名是:{}", fileName);

        Date date = new Date();
        String dateStr = "/"+new SimpleDateFormat("yyyy/MM/").format(date);
        String filePath = myDirPath + myPrefix + dateStr + fileName;
        //filePath是:D:/myFile01/shop/2023/04/8bc8bcf5-4e81-48ca-aced-94f0441cc80b.jpg
        log.info("filePath是:{}", filePath);

        File file = new File(filePath);
        if( !file.exists()){
            file.mkdirs();
        }

        try {
            pic.transferTo(new File(filePath));
        } catch (IOException e) {
            String message = "上传失败";
            log.warn(message);
        }
        return  JsonResult.success( myPrefix + dateStr + fileName);
    }


    /**
     * 删除图片
     * @param url 图片跟径
     * @return 是否删除成功
     */
    @PostMapping("/deleteByUrl")
    public JsonResult deleteByUrl(String url){
        log.info("删除图片收到的url是:{}", url);
        String filePath = myDirPath + url;
        boolean isSuccess = new File(filePath).delete();
        return JsonResult.success(isSuccess);
    }
}



















